package com.siyuanren.gcocp.web;

import cn.hutool.http.HttpUtil;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.siyuanren.gcocp.common.web.bean.Result;
import com.siyuanren.gcocp.consts.RedisConsts;
import com.siyuanren.gcocp.service.OrderService;
import com.siyuanren.gcocp.util.VaildUtil;
import com.siyuanren.gcocp.vo.CreateOrderVO;
import com.siyuanren.gcocp.vo.FreeCourseOrderVO;
import com.siyuanren.gcocp.web.wx.BaseWxController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author guwr
 */
@Controller
@RequestMapping("/course")
@Slf4j
public class WxOrderController extends BaseWxController {

    @Autowired
    private OrderService orderService;

    /**
     * 支付订单
     */
        @RequestMapping("createOrder")
        @ResponseBody
        public Result createOrder(HttpServletRequest request, CreateOrderVO vo) {
            String repeatKey = String.format(RedisConsts.REPEAT, getUserId());
            log.info("repeatKey_{}", repeatKey);
            Boolean exists = jedisFacade.exists(repeatKey);
            if (exists) {
                log.error("订单重复提交");
                return new Result(-1, "请勿重复提交订单");
            }
        // 创建并保存订单
        String clientIP = HttpUtil.getClientIP(request);
        vo.setClientIP(clientIP);
        vo.setUserId(getUserId());
        WxPayMpOrderResult result = orderService.createOrder(vo);

        jedisFacade.del(repeatKey);
        return new Result(result);
    }

    /**
     * 免费课程,直接加入. 不需要微信支付
     * @param vo
     * @return
     */
    @RequestMapping("freeCourseOrder")
    @ResponseBody
    public Result freeCourseOrder(FreeCourseOrderVO vo) throws Exception {
        VaildUtil.check(vo);
        vo.setUserId(getUserId());
        orderService.freeCourseOrder(vo);
        return new Result();
    }
}
